package com.uwantsoft.business.service.domain.park.search.statusupdator;

import com.uwantsoft.business.service.domain.park.search.SearchedPark;
import com.uwantsoft.business.service.domain.park.search.query.NearbyParkQuerier;
import com.uwantsoft.business.service.infrastructure.ParkRepository;
import com.uwantsoft.util.JodaUtils;
import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Zhang Hui on 2015/5/12.
 */
public class ParksStatusResolver {
    private final static int MAXIMUM_DURATION = 60;

    private DateTime startTime = JodaUtils.now();
    private DateTime expirationTime = startTime.plusSeconds(MAXIMUM_DURATION);
    private NearbyParkQuerier parkQuerier;


    public ParksStatusResolverResult resolve(List<String> parkGuids) {
        List<SearchedPark> searchedParks = parkQuerier.query(parkGuids.toArray(new String[parkGuids.size()]));
        return new ParksStatusResolverResult(expirationTime, searchedParks);
    }
}

class ParksStatusResolverResult {
    private DateTime expirationTime;
    private List<SearchedPark> searchedParks;

    public ParksStatusResolverResult(DateTime expirationTime, List<SearchedPark> searchedParks) {
        this.expirationTime = expirationTime;
        this.searchedParks = searchedParks;
    }

    public List<SearchedPark> parks() {
        return searchedParks;
    }

    public boolean done() {
        DateTime now = JodaUtils.now();
        if (now.isBefore(expirationTime)) {
            for (SearchedPark searchedPark : searchedParks) {
                if (searchedPark.status() == null) {
                    return false;
                }
            }
        }
        for (SearchedPark searchedPark : searchedParks) {
            if (searchedPark.status() == null) {
                searchedPark.timeout();
            }
        }
        return true;
    }

}